package com.ye.zcswzlms.controller;

import com.ye.zcswzlms.entity.Users;
import com.ye.zcswzlms.result.CommonResult;
import com.ye.zcswzlms.service.IUsersService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


/** 
* @Description:用户类
* @Author: ydh
* @email: 1575801886@qq.com
* @Date: 2021/7/20 
*/
@RestController
@RequestMapping("/user")
public class UsersController {
    @Autowired
    private IUsersService usersService;
    /** 
    * @Description: 登录控制器 
    * @Param: [user] 
    * @return: java.lang.String 
    * @Author: ydh
    * @email: 1575801886@qq.com
    * @Date: 2021/7/20 
    */
    @PostMapping("/login")
    CommonResult<Users> login( @RequestBody Users user){

        UsernamePasswordToken token = new UsernamePasswordToken(user.getStuNo(), user.getPassword());

        try {
            SecurityUtils.getSubject().login(token);
        }catch (UnknownAccountException e){
            e.printStackTrace();
            return CommonResult.getFail("用户不存在！！");
        }catch (IncorrectCredentialsException e){
            e.printStackTrace();
            return CommonResult.getFail("密码错误！！");
        }catch (Exception e) {
            e.printStackTrace();
            return CommonResult.getFail(e.getMessage());
        }
        return CommonResult.getSuccess();

    }
    /** 
    * @Description: 新注册功能 
    * @Param: [user] 
    * @return: com.ye.zcswzlms.result.CommonResult<com.ye.zcswzlms.entity.Users> 
    * @Author: ydh
    * @email: 1575801886@qq.com
    * @Date: 2021/7/21 
    */
    @PostMapping("/register")
    public CommonResult<Users> register(@RequestBody(required = false) Users user){

        usersService.register(user);
        return CommonResult.getSuccess();
    }
}
